

class CourseController extends BaseController{
    def beforeInterceptor = [action:this.auth]
    
    def index = { redirect(action:list,params:params) }

    // the delete, save and update actions only accept POST requests
    static allowedMethods = [delete:'POST', save:'POST', update:'POST']

    def list = {
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
        [ courseInstanceList: Course.list( params ), courseInstanceTotal: Course.count() ]
    }

    def show = {
        def courseInstance = Course.get( params.id )

        if(!courseInstance) {
            flash.message = "Course not found with id ${params.id}"
            redirect(action:list)
        }
        else { return [ courseInstance : courseInstance,
             numberOfEmployees: courseInstance.getListOfEmployees().size()
            ] }
    }

    def delete = {
        def courseInstance = Course.get( params.id )
        if(courseInstance) {
            try {
                courseInstance.delete(flush:true)
                flash.message = "Course ${params.id} deleted"
                redirect(action:list)
            }
            catch(org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "Course ${params.id} could not be deleted"
                redirect(action:show,id:params.id)
            }
        }
        else {
            flash.message = "Course not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def edit = {
        def courseInstance = Course.get( params.id )

        if(!courseInstance) {
            flash.message = "Course not found with id ${params.id}"
            redirect(action:list)
        }
        else {
            return [ courseInstance : courseInstance ]
        }
    }

    def update = {
        def courseInstance = Course.get( params.id )
        if(courseInstance) {
            if(params.version) {
                def version = params.version.toLong()
                if(courseInstance.version > version) {
                    
                    courseInstance.errors.rejectValue("version", "course.optimistic.locking.failure", "Another user has updated this Course while you were editing.")
                    render(view:'edit',model:[courseInstance:courseInstance])
                    return
                }
            }
            courseInstance.properties = params
            if(!courseInstance.hasErrors() && courseInstance.save()) {
                flash.message = "Course ${params.id} updated"
                redirect(action:show,id:courseInstance.id)
            }
            else {
                render(view:'edit',model:[courseInstance:courseInstance])
            }
        }
        else {
            flash.message = "Course not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def create = {
        def courseInstance = new Course()
        courseInstance.properties = params
        return ['courseInstance':courseInstance]
    }

    def save = {
        def courseInstance = new Course(params)
        if(!courseInstance.hasErrors() && courseInstance.save()) {
            flash.message = "Course ${courseInstance.id} created"
            redirect(action:show,id:courseInstance.id)
        }
        else {
            render(view:'create',model:[courseInstance:courseInstance])
        }
    }

     def delete_employee = {
        [ employeeList: Course.get(params.id).getListOfEmployees(), id: params.id ]
    }

    def save_deleted_employee = {
        String[] del = request.getParameterValues("employeeid")
        def courseInstance = Course.get(params.id)
        for(String x : del){
            int delMode
            if(session.mode == null || session.mode.equalsIgnoreCase("sandbox")){
                delMode=1
            }
            else{
                delMode=0
            }
            courseInstance.delEmployee(Employee.get(x), delMode)
        }
        flash.message = "Employees deleted from the course"
        redirect(action:show, id : params.id)
    }

    /*def add_employee = {
        def p = Course.get(params.id);
        ArrayList l = new ArrayList();
        for(Employee e : Employee.list()){
//TODO Modification in order to avoid employee from other container to show up there
            if(!p.getListOfEmployees().contains(e)){
                l.add(e);
            }
        }
        render(view:'add_employee',model:[ employeeList: l, courseid: params.id ])
    }*/

    def add_employee = {
        def courseInstance = Course.get(params.id);
        ArrayList l = new ArrayList();
            // test if the project is available in current mode
            if(((session.mode==null || session.mode.equalsIgnoreCase("sandbox")) && courseInstance.mode==1) || (session.mode != null && (session.mode.equalsIgnoreCase("budget")) && courseInstance.mode==0) || p.mode==2){
                // If the project mode corresponds to the current mode
                for(Employee e : Employee.list()){

                    int wantedMode
                    if(session.mode == null || session.mode.equalsIgnoreCase("sandbox")){ // if current mode = sandbox
                       wantedMode=1
                    }
                    else{   // if current mode = budget
                        wantedMode=0
                    }

                    //TODO Modification in order to avoid employee from other container to show up there
                    if(!courseInstance.getListOfEmployeesByMode(wantedMode).contains(e)){
                        l.add(e);
                    }
                }
                render(view:'add_employee',model:[ employeeList: l, courseid: params.id ])
            }
            else{
                flash.message = "Project not accessible in current mode"
                redirect(action:list)
            }
    }



    def save_added_employee = {
        String[] vals = request.getParameterValues("employeeid")
        def courseInstance = Course.get(params.courseid)
        if (courseInstance) {
            for(String v : vals){
                def employee = Employee.get(v);
                if(employee == null) {
                    System.out.println(v + " fel!");
                }
                else{
                    int addMode
                    if(session.mode == null || session.mode.equalsIgnoreCase("sandbox")){
                        addMode=1
                    }
                    else{
                        addMode=0
                    }
                    courseInstance.addEmployee(employee, addMode);
                }
            }
            if(courseInstance.save(flush:true,validate:false)) {
                if(vals.length==0){
                    flash.message = "No employees added."
                }
                else if(vals.length == 1){
                    flash.message = "New employee added." + vals[0]
                }
                else if(vals.length >= 2){
                    flash.message = "New employee added."
                }
                else
                {
                    flash.message = "No employees added, please report this as a bug."
                }
            }
            else{
                flash.message = "Cannot add new employee, no course found."

                courseInstance.errors.each {
                    println (it);
                }


            }
            redirect(action:show, id : params.courseid)
        }
        else{
            flash.message = "Course id ${params.courseid} not found"
            redirect(action:list)
        }

    }

    def changeMode = {
        //System.out.println("-"+session.mode+"-")
        Date d = new Date()
        if((session.mode==null)||(!session.mode.equalsIgnoreCase("budget"))){
              session.mode="budget"
        }
        else{
            session.mode="sandbox"
        }
        //System.out.println("-"+session.mode+"-")

        flash.message = "Mode changed"
        if(params.idCourse.equals("null")){
            redirect(controller:params.currentController,action:params.currentView)
        }
        else{
            redirect(controller:params.currentController,action:params.currentView, id:params.idCourse)
        }
    }
}
